/**
 * 
 */
package com.zmht.specedu.system.web;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zmht.specedu.frame.util.ConstantsVars;
import com.zmht.specedu.frame.util.StringUtils;
import com.zmht.specedu.vo.Teacher;

/**
 * @author tanxy
 * 
 */
public class LogonFilter implements Filter {
    /**
	 * 
	 */
    public LogonFilter() {
    }

    /*
     * (non-Javadoc)
     * 
     * @see javax.servlet.Filter#destroy()
     */
    public void destroy() {

    }

    /*
     * (non-Javadoc)
     * 
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
     * javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
	    FilterChain arg2) throws IOException, ServletException {
	HttpServletRequest httpRequest = (HttpServletRequest) arg0;
	HttpServletResponse httpResponse = (HttpServletResponse) arg1;
	HttpSession session = httpRequest.getSession();
	Teacher currentUser = (Teacher) session
		.getAttribute(ConstantsVars.USER_SESSEION_KEY);

	if (currentUser == null) {

	    if (!(httpRequest.getRequestURI().indexOf("/systemAction.do") != -1 && (StringUtils
		    .equals(httpRequest.getParameter("method"), "logon") || StringUtils
		    .equals(httpRequest.getParameter("method"), "toLogon")))) {
		StringBuffer sb = new StringBuffer();
		sb.append("<script>");
		sb.append("top.location='")
			.append(httpRequest.getContextPath()).append(
				"/systemAction.do?method=toLogon';");
		sb.append("</script>");
		Writer w = httpResponse.getWriter();
		w.write(sb.toString());
		w.flush();
		// httpRequest.getRequestDispatcher(
		// "/systemAction.do?method=toLogon"
		// ).forward(httpRequest,httpResponse);
		return;
	    }

	}

	httpResponse.setHeader("Pragma", "No-cache");
	httpResponse.setHeader("Cache-Control", "no-cache");
	httpResponse.setDateHeader("Expires", 0);
	if (arg2 != null) {
	    arg2.doFilter(arg0, arg1);
	}
    }

    /*
     * (non-Javadoc)
     * 
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    public void init(FilterConfig arg0) throws ServletException {

    }

}
